﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseFunction;
using YFTOpenAPI;
using YFTOpenAPI.Model;
using WebRequestHelp = YFTOpenAPI.WebRequestHelp;

namespace YY.Web.MyAgent.financial_information
{
    public partial class BuyShortMessage : BaseFunction.LoginHelp
    {
        private string KYZJ = "0";
        protected void Page_Load(object sender, EventArgs e)
        {
            KYZJ = BaseFunction.RequestValidate.GetQueryString("action", "");// Request.QueryString[""];
            YY.Model.agent_users model_suppliers_info = base.GetSessionModel();
            if (!IsPostBack)
            {
                lblUserName.Text = model_suppliers_info.user_name + "";
                txtCZJE.Attributes.Add("readonly", "false");
            }
        }
        /// <summary>
        /// 短信充值操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            YY.Model.agent_users getmodel_agent_users = base.GetSessionModel();
            decimal CZJE = Convert.ToDecimal(txtCZJE.Text.Trim());
            decimal Subtraction = Convert.ToDecimal(KYZJ) - CZJE;

            string Ip = ConfigurationManager.AppSettings["YFTLink"];//ConfigurationManager.AppSettings["YFTLink"];//  "http://pay.lelaozu.com"; "http://localhost:20608/"  ConfigurationManager.ConnectionStrings["YFTLink"].ConnectionString.Trim();
            string key = "yiyang";
            string action = "ExecYFTPay";
            string UserId = base.GetSessionModel().amount.ToString(); //用户编号
            string FeeRate = "0"; //交易费率 具体到字典表获取
            string Type = "16";//交易类型 具体到字典表获取
            string Fund = txtCZJE.Text;//交易金额
            string TradeContent = "购买短信";//交易内容 具体的是交易类型的名称
            string Remark = DateTime.Now.ToString() + getmodel_agent_users.user_name + "进行了短信充值交易，交易成功，交易金额为" + OpenAPI.DecryptPar(getmodel_agent_users.sms_account_balance) + " 元";//交易备注 类似 于2015-09-01 06:09:07；进行了充值交易，交易成功，完成充值。
            string OtherNameId = "b39d5ec9-7d87-4b50-9955-193d1a360123";//交易对方的编号
            string OtherName = "银付通";//交易对方的编号

            string eaction = OpenAPI.EncryptPar(action);
            string eUserId = OpenAPI.EncryptPar(UserId);
            string eFeeRate = OpenAPI.EncryptPar(FeeRate);
            string eType = OpenAPI.EncryptPar(Type);
            string eFund = OpenAPI.EncryptPar(Fund);
            string eTradeContent = OpenAPI.EncryptPar(TradeContent);
            string eRemark = OpenAPI.EncryptPar(Remark);
            string eOtherNameId = OpenAPI.EncryptPar(OtherNameId);
            string eOtherName = OpenAPI.EncryptPar(OtherName);
            if (Subtraction < 0)
            {
                MessageBox.ResponseScript(this.Page, string.Format("parent.jsprint(\"您的账户余额不足，无法充值！\",\"\")"));
                return;
            }

            if (GetHaveFinanceByUserId(UserId) == false)    //没有帐号
            {
                string eguid = OpenAPI.EncryptPar(UserId); //加密参数

                //生成Md5校验码    (所有参数加密后相加)
                string Md5 = OpenAPI.MD5Encrypt(eguid, key);

                /*发送请求*/
                string result = WebRequestHelp.PostDataToUrl("eguid=" + eguid + "&key=" + key + "&md5=" + Md5, Ip + "/HTTP/CreateFunds.aspx");
                if (result == ((int)BaseFunction.ErrorCode.FinanceError.CJSB).ToString())
                {
                    //创建失败
                    Response.Redirect("ErrorInfor.aspx?infor=会员支付账号创建失败");
                }
                else if (result == ((int)BaseFunction.ErrorCode.FinanceError.JYMSB).ToString())
                {
                    //校验码失败
                    Response.Redirect("ErrorInfor.aspx?infor=校验码失败");
                }
                else if (result == ((int)BaseFunction.ErrorCode.FinanceError.SHBDJ).ToString())
                {
                    //商户被冻结
                    Response.Redirect("ErrorInfor.aspx?infor=商户被冻结");
                }
                else if (result == ((int)BaseFunction.ErrorCode.FinanceError.SHBCZ).ToString())
                {
                    //商户不存在
                    Response.Redirect("ErrorInfor.aspx?infor=商户不存在");
                }
                else if (result == ((int)BaseFunction.ErrorCode.FinanceError.HYYCZ).ToString())
                {
                    //创建失败 会员已存在
                    Response.Redirect("ErrorInfor.aspx?infor=创建失败 会员已存在");
                }
                else
                {
                    if (UpdateHaveFinanceStatus(UserId))
                    {
                        //创建成功
                    }
                }
            }
            else
            {
                
                string Md5 = OpenAPI.MD5Encrypt(eaction + eFeeRate + eUserId + eType + eFund + eTradeContent + eRemark + eOtherNameId + eOtherName, key);

                string result = WebRequestHelp.PostDataToUrl("eFeeRate=" + eFeeRate + "&eguid=" + eUserId + "&eType=" + eType + "&eFund=" + eFund + "&eTradeContent=" + eTradeContent + "&eRemark=" + eRemark + "&eOtherNameId=" + eOtherNameId + "&eOtherName=" + eOtherName + "&key=" + key + "&eaction=" + eaction + "&md5=" + Md5, Ip + "/HTTP/YFTPay.aspx");
                if (result == "1000")
                {
                    //校验码失败
                    Response.Redirect("ErrorInfor.aspx?infor=校验码失败");
                }
                else
                {
                    if (result == "0")
                    {
                        MessageBox.ResponseScript(this.Page, string.Format("parent.jsprint(\"充值失败！\",\"\")"));
                    }
                    else
                    {
                        MessageBox.ResponseScript(this.Page, string.Format("parent.jsprint(\"充值成功，跳转至首页！\",\"/admin/center.aspx\")"));

                        //累加本地短信条数
                        Fund = txtCZTS.Text;
                        decimal _sms_account_balance = decimal.Parse(OpenAPI.DecryptPar(BaseFunction.StaticTableClass.agent_users_Help.bll_agent_users.GetModel(base.GetSessionAgentId())
                                   .sms_account_balance));
                        Fund = (decimal.Parse(Fund) + _sms_account_balance).ToString();

                        //更新商户表
                        getmodel_agent_users.sms_account_balance = OpenAPI.EncryptPar(Fund);
                        BaseFunction.StaticTableClass.agent_users_Help.bll_agent_users.Update(getmodel_agent_users);
                    }
                }
            }
        }

        /// <summary>
        /// 用户是否已有财务账号
        /// </summary>
        private bool GetHaveFinanceByUserId(string userid)
        {
            string sqlstr = " amount = '" + userid + "'";
            DataSet ds = BaseFunction.StaticTableClass.agent_users_Help.bll_agent_users.GetList(sqlstr);
            string HaveFinance = ds.Tables[0].Rows[0]["amount"].ToString();
            if (HaveFinance == "")
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 创建财务账号
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        private bool UpdateHaveFinanceStatus(string userid)
        {
            string sqlstr = "update tb_agent_users set amount = '" + userid + "'";
            if (BaseFunction.StaticTableClass.agent_users_Help.ExecuteSql(sqlstr))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}